﻿using JinJun.EF.Permission.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JinJun.EF.Permission.BLL
{
   public class RoleService : BaseService<Role>
    {

        /// <summary>
        /// 添加两表Role,ModuleRole
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="roleId"></param>
        /// <param name="moduleId"></param>
        /// <returns></returns>
        public bool Add(Role role, ModuleRole module)
        {
            //创建实例
            using (var db = new PermissionEntities())
            {
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        //添加第一张表
                        db.Role.Add(role);
                        //保存
                        db.SaveChanges();

                        //添加第二张表
                        module.RoleId = role.Id;
                        db.ModuleRole.Add(module);
                        //保存
                        db.SaveChanges();
                        //提交
                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        //回滚
                        tran.Rollback();
                        return false;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 添加三表Role,RoleFunctionPermission,ModuleRole
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="roleId"></param>
        /// <param name="moduleId"></param>
        /// <returns></returns>
        public bool Add(Role role, List<RoleFunctionPermission> roleFunctionList, ModuleRole module)
        {
            //创建实例
            using (var db = new PermissionEntities())
            {
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        //第一种事务
                        //添加第一张表
                        db.Role.Add(role);
                        //保存
                        db.SaveChanges();

                        //添加第二张表
                        for (int i = 0; i < roleFunctionList.Count; i++)
                        {
                            roleFunctionList[i].RoleId = role.Id;
                            db.RoleFunctionPermission.Add(roleFunctionList[i]);
                        }

                        //添加第三张表
                        module.RoleId = role.Id;
                        db.ModuleRole.Add(module);
                        //保存
                        db.SaveChanges();
                        //提交
                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        //回滚
                        tran.Rollback();
                        return false;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 修改权限
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="roleId"></param>
        /// <param name="moduleId"></param>
        /// <returns></returns>
        public bool Update(Role role, List<RoleFunctionPermission> newRoleFunctionList, List<RoleFunctionPermission> oldRoleFunctionList, ModuleRole moduleRole)
        {
            //创建实例
            using (var db = new PermissionEntities())
            {
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        //第一种事务
                        //修改第一张表
                        db.Entry(role).State = EntityState.Modified;

                        //修改第二张表
                        //查找主键值的实体
                        for (int i = 0; i < oldRoleFunctionList.Count; i++)
                        {
                            var entity = db.RoleFunctionPermission.Find(oldRoleFunctionList[i].Id);
                            if (entity != null)
                            {
                                db.RoleFunctionPermission.Remove(entity);
                            }
                        }
                        //添加第二张表
                        for (int i = 0; i < newRoleFunctionList.Count; i++)
                        {
                            newRoleFunctionList[i].RoleId = role.Id;
                            db.RoleFunctionPermission.Add(newRoleFunctionList[i]);
                        }

                        //修改第三张表
                        db.Entry(moduleRole).State = EntityState.Modified;
                        //保存
                        db.SaveChanges();
                        //提交
                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        //回滚
                        tran.Rollback();
                        return false;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 修改权限
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="roleId"></param>
        /// <param name="moduleId"></param>
        /// <returns></returns>
        public bool Update(Role role, List<RoleFunctionPermission> oldRoleFunctionList,ModuleRole moduleRole)
        {
            //创建实例
            using (var db = new PermissionEntities())
            {
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        //第一种事务
                        //修改第一张表
                        db.Entry(role).State = EntityState.Modified;

                        //查找主键值的实体
                        //删除
                        for (int i = 0; i < oldRoleFunctionList.Count; i++)
                        {
                            var entity = db.RoleFunctionPermission.Find(oldRoleFunctionList[i].Id);
                            if (entity != null)
                            {
                                db.RoleFunctionPermission.Remove(entity);
                            }
                        }

                        //修改第三张表
                        db.Entry(moduleRole).State = EntityState.Modified;
                        //保存
                        db.SaveChanges();
                        //提交
                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        //回滚
                        tran.Rollback();
                        return false;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 删除三表Role,RoleFunctionPermission,ModuleRole
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="roleId"></param>
        /// <param name="moduleId"></param>
        /// <returns></returns>
        public bool Delete(Role role, List<RoleFunctionPermission> roleFunctionList, ModuleRole moduleRole)
        {
            //创建实例
            using (var db = new PermissionEntities())
            {
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        //删除第一张表
                        db.Entry(role).State = EntityState.Deleted;

                        //删除第二张表
                        //查找主键值的实体
                        for (int i = 0; i < roleFunctionList.Count; i++)
                        {
                            var entity = db.RoleFunctionPermission.Find(roleFunctionList[i].Id);
                            if (entity != null)
                            {
                                db.RoleFunctionPermission.Remove(entity);
                            }
                        }

                        //删除第三张表
                        db.Entry(moduleRole).State = EntityState.Deleted;
                        //保存
                        db.SaveChanges();
                        //提交
                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        //回滚
                        tran.Rollback();
                        return false;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 多表连接查询
        /// </summary>
        /// <returns></returns>
        public List<RoleUserQuery> GetRoleList()
        {
            //创建List对象
            List<RoleUserQuery> adminUserQueries = new List<RoleUserQuery>();
            //创建实例
            using (var db = new PermissionEntities())
            {
                var result = (from a in db.Role
                             join b in db.AdminUserRole
                             on a.Id equals b.RoleId into dc
                             from dci in dc.DefaultIfEmpty()
                             join c in db.AdminUser
                             on dci.AdminUserId equals c.Id into da
                             from dbi in da.DefaultIfEmpty()
                             group new {a,dbi} by new{a.Id,a.Remark,a.Name} 
                             into e
                             select new {e}).AsEnumerable().Select(a=>new
                             RoleUserQuery()
                             {
                                 RoleId = a.e.Key.Id,
                                 RoleName = a.e.Key.Name,
                                 Remark = a.e.Key.Remark,
                                 Count = a.e.Count(),
                                 UserName = a.e.First().dbi==null?"空": string.Join(",", a.e.Select(b => b.dbi.Name))
                             });
                return result.ToList();
            }
        }

    }
}
